'use strict'
//titbit框架的设计机制
const titbit=require('titbit');
const {cookie,session}=require('titbit-toolkit')
const app=new titbit({
    debug:true
})
app.use((new cookie()).mid())
//一定要在cookie之后，session是基于cookie的
app.use((new session()).mid())
app.use(async(c,next)=>{
    console.log('just for home')
    await next()
//添加只针对home分组执行的中间件
},{group:'home'})
app.use(async (c,next)=>{
    //检测有没有cookie，发送消息头
    if(c.headers['cookie']===undefined){
        c.setHeader('set-cookie','key=12345')
    }
    await next()
})

app.get('/',async c=>{
    console.log('success');
    c.res.body='success'
},{name:'首页',group:'home'})

app.get('/cookie',async c=>{
    c.res.body=c.headers['cookie'] || '还没有设置cookie'
})

app.get('/login',async c=>{
    c.res.body=`<!DOCTYPE html><html>
    <head>
        <meta charset='utf-8'>
    </head>
    <body>
        <form action="login" method="post">
            <input type="text" name="username">
            <input type="password" name="passwd">
            <input type="submit" value='Login'>
        </form>
    </body>
    </html>
    `
})
app.post('/login',async c=>{
    //提交数据解析到c.body
    let {username,passwd}=c.body
    if(username ==='testuser' && passwd==='1234'){
        console.log('成功')
        c.setSession('is_login',true)
        //登陆成功跳转到首页
        c.status(301)
        c.setHeader('Location','/')
        
        console.log('成功1')
    }else{
        //登陆失败跳转回登陆界面
        c.status(301)
        c.setHeader('Location','/login')
    }
})
app.run(5023)